/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * This file is part of retabel.
 *
 * Copyright (c) 2011 by individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution
 * for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.retabel.web.rest;

import org.retabel.persistence.entity.configuration.ConfigAttribute;
import org.retabel.persistence.entity.configuration.ConfigSet;
import org.retabel.service.manager.ConfigSetManager;
import xsd.configset.ConfigAttributeList;
import xsd.configset.ConfigSetList;
import xsd.configset.ConfigSets;
import xsd.configset.ObjectFactory;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

/**
 * Config set REST interface implementation
 * <p/>
 * <h3>Extra-Info</h3>
 * Created: 10:19 16.07.11
 *
 * @author Peter Herber
 * @version 1.0
 */
@Path("/config/configsets/")
@Stateless
public class ConfigSetServiceBean extends RestServiceBean {

    @EJB
    private ConfigSetManager configSetManager;


    /**
     * Retrieve a ranged list of available configuration sets.
     *
     * @param first   the index of the first configuration set to retrieve.
     * @param maxRows the maximum number of matches to retrieve.
     * @return xml containing the list of configuration sets matching the given search criteria.
     */
    @GET
    @Produces(MediaType.TEXT_XML)
    public Response getConfigSets(@QueryParam("first") @DefaultValue("0") Integer first,
                                                 @QueryParam("maxRows") @DefaultValue("100")Integer maxRows) {
        int maxRowsWithFallback = maxRows != null ? maxRows : getDefaultMaxResultsPerPage();
        int firstWithFallback = first != null ? first : 0;

        int count = configSetManager.count();
        ConfigSet[] configSets = configSetManager.findRange(firstWithFallback, maxRowsWithFallback);

        ObjectFactory of = new ObjectFactory();

        ConfigSets result = of.createConfigSets();
        result.setStart(firstWithFallback);
        result.setRows(configSets.length);
        result.setCount(count);

        ConfigSetList configSetList = of.createConfigSetList();
        result.setList(configSetList);

        for (ConfigSet configSet : configSets) {
            xsd.configset.ConfigSet xmlConfigSet = of.createConfigSet();
            xmlConfigSet.setName(configSet.getName());

            ConfigAttributeList configAttributeList = of.createConfigAttributeList();
            xmlConfigSet.setAttributes(configAttributeList);

            for (ConfigAttribute configAttribute : configSet.getConfigAttributes()) {
                xsd.configset.ConfigAttribute xmlConfigAttribute = of.createConfigAttribute();
                xmlConfigAttribute.setName(configAttribute.getName());
                xmlConfigAttribute.setType(configAttribute.getType());
                xmlConfigAttribute.setValue(configAttribute.getValue());

                configAttributeList.getAttribute().add(xmlConfigAttribute);
            }

            configSetList.getConfigSet().add(xmlConfigSet);
        }

        return Response.ok(result).build();
    }

    /**
     * Retrieve the config set by name.
     *
     * @param name the name of the config set to retrieve.
     * @return xml containing the config set data.
     */
    @GET
    @Path("/{name}")
    @Produces(MediaType.TEXT_XML)
    public Response getConfigSet(@PathParam("name") String name) {
        ConfigSet configSet = configSetManager.findByName(name);

        if (configSet == null) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }

        ObjectFactory of = new ObjectFactory();

        xsd.configset.ConfigSet xmlConfigSet = of.createConfigSet();
        xmlConfigSet.setName(configSet.getName());

        ConfigAttributeList xmlConfigAttributeList = of.createConfigAttributeList();
        xmlConfigSet.setAttributes(xmlConfigAttributeList);

        for (ConfigAttribute configAttribute : configSet.getConfigAttributes()) {
            xsd.configset.ConfigAttribute xmlConfigAttribute = of.createConfigAttribute();
            xmlConfigAttribute.setName(configAttribute.getName());
            xmlConfigAttribute.setType(configAttribute.getType());
            xmlConfigAttribute.setValue(configAttribute.getValue());

            xmlConfigAttributeList.getAttribute().add(xmlConfigAttribute);
        }

        return Response.ok(xmlConfigSet).build();
    }

    /**
     * Add a new configuration set.
     *
     * @param name    the unique config set name to add.
     * @param uriInfo the uri info context used for logging purposes.
     * @return plain/text log lines.
     */
    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.TEXT_PLAIN)
    public Response addConfigSet(@FormParam("name") String name, @Context UriInfo uriInfo) {
        PlainTextResponseBuilder response = new PlainTextResponseBuilder(uriInfo);

        response.println("Attempting to store config set: " + name);
        configSetManager.addConfigSet(name);

        return response.getResponse();
    }

    /**
     * Delete an config set by it's unique name.
     *
     * @param name    the unique config set name.
     * @param uriInfo the uri info context used for logging purposes.
     * @return plain/text log lines.
     */
    @DELETE
    @Path("/{name}")
    @Produces(MediaType.TEXT_PLAIN)
    public Response deleteConfigSet(@PathParam("name") String name, @Context UriInfo uriInfo) {
        PlainTextResponseBuilder response = new PlainTextResponseBuilder(uriInfo);

        response.println("Deleting config set: " + name);
        configSetManager.removeConfigSet(name);

        return response.getResponse();
    }

    /**
     * Add a new config attribute.
     *
     * @param configSetName          the unique config set name.
     * @param configSetAttributeName the unique config attribute name.
     * @param value                  the new config attribute value.
     * @param uriInfo                the uri info context used for logging purposes.
     * @return plain/text log lines.
     */
    @POST
    @Path("/{configSetName}")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.TEXT_PLAIN)
    public Response addConfigAttribute(@PathParam("configSetName") String configSetName,
                                       @FormParam("name") String configSetAttributeName, @FormParam("value") String value,
                                       @Context UriInfo uriInfo) {
        throw new UnsupportedOperationException();
    }

    /**
     * Update a config attribute.
     *
     * @param configSetName          the unique config set name.
     * @param configSetAttributeName the unique config attribute name.
     * @param value                  the new config attribute value.
     * @param uriInfo                the uri info context used for logging purposes.
     * @return plain/text log lines.
     */
    @PUT
    @Path("/{configSetName}/{configSetAttributeName}")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.TEXT_PLAIN)
    public Response updateConfigAttribute(@PathParam("configSetName") String configSetName,
                                          @PathParam("configSetAttributeName") String configSetAttributeName,
                                          @FormParam("value") String value, @Context UriInfo uriInfo) {
        PlainTextResponseBuilder response = new PlainTextResponseBuilder(uriInfo);
        response.println("Updateing config attribute: " + configSetName + "[" + configSetAttributeName + "] -> " + value);
        ConfigSet configSet = configSetManager.findByName(configSetName);

        if (configSet == null) {
            return response.getResponse();
        }

        ConfigAttribute configAttribute = configSet.getConfigAttribute(configSetAttributeName);
        if (configAttribute == null) {
            response.println("Config attribute not found: " + configSetAttributeName);

            return response.getResponse();
        }
        configAttribute.setValue(value);

        return response.getResponse();
    }

    /**
     * Delete a config attribute.
     *
     * @param configSetName          the unique config set name.
     * @param configSetAttributeName the unique config attribute name.
     * @param uriInfo                the uri info context used for logging purposes.
     * @return plain/text log lines
     */
    @DELETE
    @Path("/{configSetName}/{configSetAttributeName}")
    @Produces(MediaType.TEXT_PLAIN)
    public Response deleteConfigAttribute(@PathParam("configSetName") String configSetName,
                                          @PathParam("configSetAttributeName") String configSetAttributeName,
                                          @Context UriInfo uriInfo) {
        throw new UnsupportedOperationException();
    }
}
